import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'dart:ui' as ui;

class JoystickPainter extends CustomPainter {
  final Offset center;
  final double radiusInnerCircle;
  final double radiusOuterCircle;
  final double radiusTrack;
  final Offset blueDotPosition;
  final Function(double)? onAngleChanged;

  JoystickPainter({
    required this.center,
    required this.radiusInnerCircle,
    required this.radiusOuterCircle,
    required this.radiusTrack,
    required this.blueDotPosition,
    this.onAngleChanged,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // Create a Paint object for the shadow
    Paint shadowPaint = Paint()
      ..maskFilter = ui.MaskFilter.blur(ui.BlurStyle.normal, 5.0)
      ..color = Colors.black..style = PaintingStyle.stroke..strokeWidth = 5.0;
    final Paint outWhiteCirclePaint = Paint()..color = Colors.white..style = PaintingStyle.stroke..strokeWidth = 10.0;
    final Paint outerCirclePaint = Paint()..color = Colors.black..style = PaintingStyle.stroke..strokeWidth = 10.0;
    final Paint innerCirclePaint = Paint()..color = Colors.grey..style = PaintingStyle.stroke..strokeWidth = 10.0;
    final Paint blueDotPaint = Paint()..color = Colors.blue;

    // Draw the shadow first
    // canvas.drawCircle(
    //     center,
    //     radiusTrack,
    //     shadowPaint);

    // Draw the grey ring (track)
    canvas.drawCircle(center, radiusTrack, outWhiteCirclePaint);


    // Draw the white outer circle
    canvas.drawCircle(center, radiusOuterCircle, outerCirclePaint);

    // Draw the white inner circle
    canvas.drawCircle(center, radiusInnerCircle, innerCirclePaint);

    // Draw the blue dot
    canvas.drawCircle(blueDotPosition, 20, blueDotPaint);

    // Draw arrows at four positions
    final arrowSize = 30.0;
    final arrowPath = Path()
      ..moveTo(-arrowSize / 2, arrowSize / 2)
      ..lineTo(0, -arrowSize / 2)
      ..lineTo(arrowSize / 2, arrowSize / 2)
      ..close();

    final Paint arrowPaint = Paint()..color = Colors.black;

    void drawArrow(double angle) {
      canvas.save();
      canvas.translate(center.dx, center.dy);
      canvas.rotate(angle);
      canvas.translate(0, -radiusOuterCircle - 10); // Position the arrow outside the white circle
      canvas.drawPath(arrowPath, arrowPaint);
      canvas.restore();
    }

    // Draw arrows pointing up, down, left, and right
    drawArrow(0); // Up
    drawArrow(math.pi); // Down
    drawArrow(-math.pi / 2); // Left
    drawArrow(math.pi / 2); // Right

    // Calculate angle and notify listeners if it has changed
    if (onAngleChanged != null && blueDotPosition != center) {
      final dx = blueDotPosition.dx - center.dx;
      final dy = blueDotPosition.dy - center.dy;
      final angle = ((math.atan2(dy, dx) * 180 / math.pi) + 90) % 360;
      onAngleChanged!(angle);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}